const CompressionWebpackPlugin = require('compression-webpack-plugin')
const productionGzipExtensions = ['js', 'css', 'html']
const path = require('path')
const resolve = dir => {
  return path.join(__dirname, dir)
}

module.exports = {
  publicPath: './', // 相对路径
  lintOnSave: process.env.NODE_ENV === 'development', // 开发环境开启代码检查
  productionSourceMap: false, // 打包禁止生成 .map 文件，加快打包速度

  //反向代理配置
  // devServer: {
  //   proxy: {
  //     '/api': {
  //       target: '/target.com', //目标地址
  //       // ws: true, //// 是否启用websockets
  //       changeOrigin: true, //开启代理
  //       pathRewrite: { '^/api': '/' } //重写路径
  //     }
  //   }
  // },

  configureWebpack: {
    resolve: {
      alias: {
        '@': resolve('src'),
        '@a': resolve('src/assets'),
        '@c': resolve('src/components'),
        '@v': resolve('src/views'),
        '@u': resolve('src/utils'),
        '@i': resolve('src/api')
      }
    },
    plugins: [
      // Gzip压缩
      new CompressionWebpackPlugin({
        filename: '[path].gz[query]',
        algorithm: 'gzip',
        test: new RegExp('\\.(' + productionGzipExtensions.join('|') + ')$'), //匹配文件名
        threshold: 10240, //对10K以上的数据进行压缩
        minRatio: 0.8,
        deleteOriginalAssets: false //是否删除源文件
      })
    ]
  },

  chainWebpack(config) {
    // 提前预加载提高切换路由的体验
    config.plugin('preload').tap(() => [
      {
        rel: 'preload',
        fileBlacklist: [/\.map$/, /hot-update\.js$/, /runtime\..*\.js$/],
        include: 'initial'
      }
    ])

    // 使用 script-ext-html-webpack-plugin 插件将runtime内链在 index.html
    config.when(process.env.NODE_ENV !== 'development', config => {
      config
        .plugin('ScriptExtHtmlWebpackPlugin')
        .after('html')
        .use('script-ext-html-webpack-plugin', [
          {
            inline: /runtime\..*\.js$/
          }
        ])
        .end()
      /** chunks 资源分块，如果使用了某些长期不会改变的库，像element-ui ，打包完成有 600 多 KB
          包含在默认 vendor 中显然不合适，每次用户都要加载这么大的文件体验不好，所以要单独打包 */
      config.optimization.splitChunks({
        chunks: 'all',
        cacheGroups: {
          libs: {
            name: 'chunk-libs',
            test: /[\\/]node_modules[\\/]/,
            priority: 10,
            chunks: 'initial'
          },
          elementUI: {
            name: 'chunk-elementUI',
            priority: 20,
            test: /[\\/]node_modules[\\/]_?element-ui(.*)/
          },
          commons: {
            name: 'chunk-commons',
            test: resolve('src/components'),
            minChunks: 3,
            priority: 5,
            reuseExistingChunk: true
          }
        }
      })
      // 将runtime 代码单独抽取打包
      config.optimization.runtimeChunk('single')
    })
  },

  // rem适配
  css: {
    loaderOptions: {
      postcss: {
        plugins: [
          require('postcss-px2rem-exclude')({
            remUnit: 16,
            exclude: /media.scss/
          })
        ]
      }
    }
  }
}
